package com.ruoyi.app.interceptor;

import com.google.gson.Gson;
import com.ruoyi.cms.domain.CrmMember;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.employee.domain.CrmEmployee;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class JWTLoginInterceptor  implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(JWTLoginInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        //String accessToken = request.getHeader("Authorization");
        String accessToken = JWTUtil.getRequestToken(request);
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("LoginInterceptorPreHandle :" + accessToken);
        if(StringUtils.isNotEmpty(accessToken)) {
            CrmMember memberDTO = (CrmMember) redisCache.getCacheObject(Constants.MEMBER_TOKEN + accessToken);
            redisCache.expire(Constants.MEMBER_TOKEN + accessToken,1, TimeUnit.HOURS);
            if (memberDTO != null) {
                SessionUtil.setLoginUser(memberDTO);
                return true;
            }
        }
        response.setContentType("text/html;charset=UTF-8");
        ServletOutputStream sos = response.getOutputStream();
        AjaxResult.error(HttpStatus.UNAUTHORIZED,"请授权");
        Gson gson=new Gson();
        String ss=gson.toJson(AjaxResult.error(HttpStatus.UNAUTHORIZED,"请授权"));
        sos.write(ss.getBytes("UTF-8"));
         return false;
    }

//    /**
//     * 开发不加token
//     * @param request
//     * @param response
//     * @param handler
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
//            throws Exception {
//        return false;
//    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
